const app = getApp()
import Toast from '@vant/weapp/toast/toast';

Page({
  data: {
    wd: "",
    songs: [],
    currentSong: {
      poster: "",
      name: "",
      author: "",
      src: ""
    },
    currentId: null,
    limit: 15,
    page: 1
  },
  onChange(event) {
    this.setData({
      wd: event.detail
    })
  },
  onSearch() {
    const wd = this.data.wd
    const limit = this.data.limit
    const self = this
    if(!wd) {
      Toast('关键词不能为空');
    }
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    app.http({
      url: `https://koo-music.vercel.app/search?keywords=${wd}&limit=${limit}`
    }).then(res => {
      const songs = res.data.result.songs.map(item => {
        // item.artistsName = item.artists
        // console.log(item.artists.map(art => {
        //   return art.name
        // }))
        item.artistsName = item.artists.map(art => art.name).join()
        return item
      })

      self.setData({
        // songs: res.data.result.songs
        songs,
      })
      console.log(self.data.songs)
    }).catch(e => {

    }).finally(() => {
      Toast.clear()
    })
  },
  onReachBottom() {
    const self = this
    console.log("加载下一页")
    this.setData({
      page: ++this.data.page
    })
    const wd = this.data.wd
    const limit = this.data.limit
    const offset = this.data.limit * (this.data.page - 1)
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    app.http({
      url: `https://koo-music.vercel.app/search?keywords=${wd}&limit=${limit}&offset=${offset}`
    }).then(res => {
      const songs = res.data.result.songs.map(item => {
        item.artistsName = item.artists.map(art => art.name).join()
        return item
      })

      self.setData({
        songs: [...self.data.songs, ...songs],
      })
      console.log(self.data.songs)
    }).catch(e => {

    }).finally(() => {
      Toast.clear()
    })
  },
  onReady() {
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  async onPlay(event) {
    const self = this
    const { id } = event.currentTarget.dataset
    const res = await app.http({
      url: `https://koo-music.vercel.app/song/detail?ids=${id}`
    })
    // console.log(res.data)
    // console.log(res.data.songs[0].al)
    // console.log(res.data.songs[0].ar)
    this.setData({
      currentId: id,
      "currentSong.name": res.data.songs[0].name,
      "currentSong.poster": res.data.songs[0].al.picUrl,
      "currentSong.author": res.data.songs[0].ar[0].name,
      "currentSong.src": `https://music.163.com/song/media/outer/url?id=${id}.mp3`
    })
    console.log(this.data.currentSong)

    setTimeout(function () {
      self.audioCtx.play()
    }, 100)

    // /song/detail?ids=347230
  }
})
